package org.lds.scheduled.job.admin.starter.holder;

import org.lds.scheduled.job.common.model.WorkerModel;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WorkerHolder {
    /**
     * 有效worker缓存
     */
    private final Map<Long, WorkerModel> cache = new ConcurrentHashMap<>();

    public void save(Long id, Long appId, String address) {
        WorkerModel workerModel = cache.get(id);
        if (workerModel != null &&
                workerModel.getId().equals(id) &&
                workerModel.getAppId().equals(appId) &&
                workerModel.getAddress().equals(address)) return;
        cache.put(id, WorkerModel.builder()
                        .id(id)
                        .appId(appId)
                        .address(address)
                        .build());
    }

    public void remove(Long id) {
        cache.remove(id);
    }

    public Map<Long, WorkerModel> getCache() {
        return cache;
    }
}
